package me.midday;

import me.midday.activator.Activator;
import me.midday.activator.Sigmoid;
import me.midday.matrix.Matrix;
import me.midday.matrix.MatrixException;

/**
 * Created by wuzheng on 17-11-9.
 */
public class Perceptron {

    private Perceptron(){}

    private int featureNum = 0;
    private Activator activator = new Sigmoid();
    private  Matrix  weights ;
    private double bias = 0.0 ;

    public Perceptron(int featureNum, Activator activator){
        this.featureNum = featureNum;
        this.activator = activator;
        this.weights = new Matrix(featureNum, 1);
    }

    public Perceptron(int featureNum){
        this.featureNum = featureNum;
        this.weights = new Matrix(featureNum, 1);
    }


    public Matrix predict(Matrix matX) throws MatrixException{

        Matrix predm = matX.dot(weights);

        Matrix h = predm.sumAll();
        h.add(this.bias);
        return h;
    }
    private void updateWeight(Matrix errorMat, Matrix trainMat, double learningRate) throws MatrixException {
        Matrix delta = errorMat.dot(trainMat).multi(learningRate);
        this.weights = this.weights.add(delta);
        this.bias = -1 * errorMat.sumAll().getValue(0, 0);
    }

    public void train(Matrix trainMat, Matrix label, int epochs, double learningRate) throws MatrixException {
        for (int epoch = 0 ; epoch < epochs; epoch++){
            System.out.println(weights);
            Matrix h = predict(trainMat);

            Matrix errorMat = h.sub(label);
            updateWeight(errorMat, trainMat, learningRate);
            System.out.println("leaning error: " + errorMat.sumAll().getValue(0, 0));
        }
    }

}
